#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
密码健康检查模块
"""
from ..database import get_db_connection
from ..utils.security import check_password_strength


def generate_password_health_report(user_id: int = None) -> dict:
    """生成密码健康报告"""
    report = {
        'total_passwords': 0,
        'weak_passwords': 0,
        'medium_passwords': 0,
        'strong_passwords': 0,
        'duplicate_passwords': 0,
        'non_compliant_passwords': 0,
        'passwords': []
    }
    
    conn = get_db_connection()
    cursor = conn.cursor()
    
    try:
        # 查询密码
        if user_id:
            cursor.execute("SELECT id, url, account, password FROM passwords WHERE user_id = ?", (user_id,))
        else:
            # 管理员查看所有密码
            cursor.execute("SELECT id, url, account, password FROM passwords")
        
        passwords = cursor.fetchall()
        report['total_passwords'] = len(passwords)
        
        # 用于检测重复密码
        password_counts = {}
        
        for password_record in passwords:
            password_text = password_record['password']
            
            # 统计密码使用次数
            if password_text in password_counts:
                password_counts[password_text] += 1
            else:
                password_counts[password_text] = 1
            
            # 检查密码强度
            strength = check_password_strength(password_text)
            
            password_info = {
                'id': password_record['id'],
                'url': password_record['url'],
                'account': password_record['account'],
                'strength': strength['strength_level'],
                'score': strength['score'],
                'feedback': strength['feedback']
            }
            
            # 统计强度分布
            if strength['strength_level'] == 'weak':
                report['weak_passwords'] += 1
            elif strength['strength_level'] == 'medium':
                report['medium_passwords'] += 1
            else:
                report['strong_passwords'] += 1
            
            report['passwords'].append(password_info)
        
        # 统计重复密码
        for password_text, count in password_counts.items():
            if count > 1:
                report['duplicate_passwords'] += count
        
        # 计算不合规密码数量（弱密码 + 重复密码）
        report['non_compliant_passwords'] = report['weak_passwords'] + report['duplicate_passwords']
        
    except Exception as e:
        print(f"生成密码健康报告时出错: {e}")
    finally:
        conn.close()
    
    return report